﻿using EFFC.Frame.Net.Base.Common;
using EFFC.Frame.Net.Module.Extend.EWRA.Attributes;
using EFFC.Frame.Net.Module.Extend.EWRA.Attributes.Validation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using EFFC.Extends.LinqDLR2SQL;
using EFFC.Frame.Net.Unit.DB;
using EFFC.Frame.Net.Unit.DB.Parameters;
using ICPFrameLib.Business;
using ICPFrameLib.Attributes;
using EFFC.Frame.Net.Base.Data.Base;

namespace XHRPMIS.Business.v1._0
{
   public class LoginUser : MyRestLogic
{
    [ActionAuth("Login")]
    [EWRARouteDesc("获取所有登录者的列表")]
    [EWRAOutputDesc("返回结果", @"{
result:[数据集]
}")]
    public override List<object> get()
    {
        SetCacheEnable(false);
        var up = DB.NewMetaUnitParameter();
        var s = from t in DB.LamdaTable(up, "EXTEND_LOGIN", "a")
                join t2 in DB.LamdaTable(up, "EXTEND_ROLE_LOGIN", "b").LeftJoin() on t.uid equals t2.loginuid
                select new
                {
                    t.uid,
                    t.loginid,
                    t.loginname,
                    t.userno,
                    t.usertype,
                    t.loginpass,
                    t2.roleno,
                    t.mobile,
                    t.qq,
                    t.avatar
                };
        var list = s.GetQueryList(up);
        var newlist = from t in list
                      group t by t.GetValue("uid") into g
                      select new
                      {
                          uid = g.First().GetValue("uid"),
                          loginid = g.First().GetValue("loginid"),
                          loginname = g.First().GetValue("loginname"),
                          userno = g.First().GetValue("userno"),
                          usertype = g.First().GetValue("usertype"),
                          loginpass = ComFunc.AESDecrypt(ComFunc.nvl(g.First().GetValue("loginpass"))),
                          mobile = g.First().GetValue("mobile"),
                          qq = g.First().GetValue("qq"),
                          avatar = g.First().GetValue("avatar"),
                          roles = (from tt in g
                                   where ComFunc.nvl(tt.GetValue("roleno")) != ""
                                   select ComFunc.nvl(tt.GetValue("roleno"))).ToList()
                      };
        return newlist.ToList<object>();
    }
    [ActionAuth("Login")]
    [EWRARouteDesc("翻页查询所有登录者的列表")]
    [EWRARoute("get", "/loginuser/list")]
    [EWRAAddInput("limit", "int", "每页笔数，当mode为Normal时需要提供", "默认为10", EFFC.Frame.Net.Base.Constants.RestInputPosition.QueryString, true)]
    [EWRAAddInput("page", "int", "指定页数，当mode为Normal时需要提供", "默认为1", EFFC.Frame.Net.Base.Constants.RestInputPosition.QueryString, true)]
    [EWRAAddInput("filter", "string", "过滤条件", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.QueryString, true)]
    [EWRAOutputDesc("返回结果", @"{
code: 'success或failed',
msg : '',
data:{
    Count_Of_OnePage:'每页笔数',
    CurrentPage:'当前页号',
    TotalPage:'总页数',
    TotalRow:'总笔数',
    QueryDatas:[数据集]
}
}")]
    object GetList()
    {
        SetCacheEnable(false);
        var up = DB.NewMetaUnitParameter();
        var s = from t in DB.LamdaTable(up, "EXTEND_LOGIN", "a")
                join t2 in DB.LamdaTable(up, "EXTEND_ROLE_LOGIN", "b").LeftJoin() on t.uid equals t2.loginuid
                where t.notnull(QueryStringD.filter, t.loginid.contains(QueryStringD.filter) || t.loginname.contains(QueryStringD.filter))
                select new
                {
                    t.uid,
                    t.loginid,
                    t.loginname,
                    t.userno,
                    t.usertype,
                    t.loginpass,
                    t2.roleno,
                    t.mobile,
                    t.qq,
                    t.avatar
                };
        var result = s.QueryByPage(up, "loginid");
        var newlist = from t in result.QueryData<FrameDLRObject>()
                      group t by t.GetValue("uid") into g
                      select new
                      {
                          uid = g.First().GetValue("uid"),
                          loginid = g.First().GetValue("loginid"),
                          loginname = g.First().GetValue("loginname"),
                          userno = g.First().GetValue("userno"),
                          usertype = g.First().GetValue("usertype"),
                          loginpass = ComFunc.AESDecrypt(ComFunc.nvl(g.First().GetValue("loginpass"))),
                          mobile = g.First().GetValue("mobile"),
                          qq = g.First().GetValue("qq"),
                          avatar = g.First().GetValue("avatar"),
                          roles = (from tt in g
                                   where ComFunc.nvl(tt.GetValue("roleno")) != ""
                                   select ComFunc.nvl(tt.GetValue("roleno"))).ToList()
                      };
        return ResultHelper.DFormQueryByPageFormat(result.Count_Of_OnePage, result.CurrentPage, result.TotalPage, result.TotalRow, newlist);
    }
    [EWRARoute("get", "/loginuser/{id}/avatar")]
    [EWRARouteDesc("获取当前登录者的头像")]
    [EWRAOutputDesc("返回结果", @"{
code:""success-成功，failed-失败"",
msg:""提示信息"",
file_url:""文件url""
}")]
    object GetCurrentAvatar(string id)
    {
        SetCacheEnable(false);
        var up = DB.NewMetaUnitParameter();
        var s = from t in DB.LamdaTable(up, "EXTEND_LOGIN", "a")
                where t.uid == id || t.loginid == id
                select t;
        if (!s.IsExists(up))
        {
            return new
            {
                code = "failed",
                msg = "当前登录账号无效"
            };
        }
        dynamic info = s.GetQueryList(up).First();
        return new
        {
            code = "success",
            msg = "",
            file_url = ComFunc.nvl(info.avatar)
        };
    }
    [EWRARoute("get", "/myavatar")]
    [EWRARouteDesc("获取当前登录者的头像")]
    [EWRAOutputDesc("返回结果", @"{
code:""success-成功，failed-失败"",
msg:""提示信息"",
file_url:""文件url""
}")]
    object GetCurrentAvatar()
    {
        SetCacheEnable(false);
        var up = DB.NewMetaUnitParameter();
        var id = TokenPayLoad.ID;
        var s = from t in DB.LamdaTable(up, "EXTEND_LOGIN", "a")
                where t.uid == id || t.loginid == id
                select t;
        if (!s.IsExists(up))
        {
            return new
            {
                code = "failed",
                msg = "当前登录账号无效"
            };
        }
        dynamic info = s.GetQueryList(up).First();
        return new
        {
            code = "success",
            msg = "",
            file_url = ComFunc.nvl(info.avatar)
        };
    }
    [EWRARoute("get", "/myinfo")]
    [EWRARouteDesc("获取当前登录者的信息")]
    [EWRAOutputDesc("返回结果", @"{
code:""success-成功，failed-失败"",
msg:""提示信息"",
data:{
    name:'当前登录者名称',
    userno:'当前登录者的userno',
    mobile:'当前登录者的手机号',
    qq:'当前登录者qq号'，
    usertype:'当前登录者的用户类型'
}
}")]
    object GetCurrentInfo()
    {
        SetCacheEnable(false);
        return new
        {
            code = "success",
            msg = "",
            data = new
            {
                name = ComFunc.nvl(TokenPayLoad["name"]),
                userno = ComFunc.nvl(TokenPayLoad["userno"]),
                mobile = ComFunc.nvl(TokenPayLoad["mobile"]),
                qq = ComFunc.nvl(TokenPayLoad["qq"]),
                usertype = ComFunc.nvl(TokenPayLoad["usertype"])
            }
        };
    }
    [ActionAuth("Login")]
    [EWRAEmptyValid("loginid,loginpass")]
    [EWRARouteDesc("新增一个登录账号")]
    [EWRAAddInput("loginid", "string", "登录账号", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.PostData, false)]
    [EWRAAddInput("loginname", "string", "登录名称", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.PostData, false)]
    [EWRAAddInput("loginpass", "string", "登录密码", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.PostData, false)]
    [EWRAAddInput("usertype", "string", "用户类型", "默认为System(取值范围为System,Student,Teacher)", EFFC.Frame.Net.Base.Constants.RestInputPosition.PostData, true)]
    [EWRAAddInput("userno", "string", "用户编号,用户类型为Student或Teacher时为其对应的编号（此时为必输）", "默认为空", EFFC.Frame.Net.Base.Constants.RestInputPosition.PostData, true)]
    [EWRAAddInput("mobile", "string", "用户手机号", "默认为空", EFFC.Frame.Net.Base.Constants.RestInputPosition.PostData, true)]
    [EWRAAddInput("qq", "string", "用户手机号", "默认为空", EFFC.Frame.Net.Base.Constants.RestInputPosition.PostData, true)]
    [EWRAAddInput("avatar", "string", "用户头像url", "默认为空", EFFC.Frame.Net.Base.Constants.RestInputPosition.PostData, true)]
    [EWRAOutputDesc("返回结果", @"{
code:""success-成功，failed-失败"",
msg:""提示信息"",
login_uid:""成功时候返回的登录账号""
}")]
    public override object post()
    {
        string loginid = ComFunc.nvl(PostDataD.loginid);
        string loginpass = ComFunc.AESEncrypt(ComFunc.nvl(PostDataD.loginpass));
        string loginname = ComFunc.nvl(PostDataD.loginname);
        string usertype = ComFunc.nvl(PostDataD.usertype);
        string userno = ComFunc.nvl(PostDataD.userno);
        string mobile = ComFunc.nvl(PostDataD.mobile);
        string qq = ComFunc.nvl(PostDataD.qq);
        string avatar = ComFunc.nvl(PostDataD.avatar);

        if (loginid == ""
           || loginname == ""
           || loginpass == "")
        {
            return new
            {
                code = "failed",
                msg = "登录账户、名称和密码不可为空"
            };
        }

        BeginTrans();
        var up = DB.NewMetaUnitParameter();

        if ((from t in DB.LamdaTable(up, "EXTEND_LOGIN", "a")
             where t.loginid == loginid
             select t).IsExists(up))
        {
            return new
            {
                code = "failed",
                msg = "登录账号已存在"
            };
        }
        var loginuid = Guid.NewGuid().ToString();
        DB.QuickInsert(up, "EXTEND_LOGIN", new
        {
            UID = loginuid,
            LoginID = loginid,
            UserNo = userno,
            LoginName = loginname,
            UserType = usertype,
            LoginPass = loginpass,
            Mobile = mobile,
            QQ = qq,
            Avatar = avatar,
            add_id = TokenPayLoad.ID,
            add_ip = ClientInfo.IP,
            add_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
            last_id = TokenPayLoad.ID,
            last_ip = ClientInfo.IP,
            last_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")

        });
        CommitTrans();
        return new
        {
            code = "success",
            msg = "新增成功",
            login_uid = loginuid
        };
    }
    [ActionAuth("Login")]
    [EWRARouteDesc("删除一个登录账号")]
    [EWRAAddInput("id", "string", "账号的UID", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.Path, false)]
    [EWRAOutputDesc("返回结果", @"根据http的状态码来识别，204标识操作成功，404表示操作识别未找到删除的资料")]
    public override bool delete(string id)
    {
        BeginTrans();
        var up = DB.NewMetaUnitParameter();
        var s = from t in DB.LamdaTable(up, "EXTEND_LOGIN", "a")
                where t.uid == id
                select t;
        if (!s.IsExists(up))
        {
            return false;
        }
        s.Delete(up);
        //删除角色登录者映射表
        (from t in DB.LamdaTable(up, "EXTEND_ROLE_LOGIN", "a")
         where t.loginuid == id
         select t).Delete(up);
        CommitTrans();
        return true;
    }
    [ActionAuth("Login")]
    [EWRARouteDesc("修改一个登录账号")]
    [EWRAAddInput("id", "string", "账号UID码", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.Path, false)]
    [EWRAAddInput("loginid", "string", "新登录账号", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.PostData, false)]
    [EWRAAddInput("loginname", "string", "登录名称", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.PostData, false)]
    [EWRAAddInput("old_loginpass", "string", "旧登录密码", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.PostData, true)]
    [EWRAAddInput("loginpass", "string", "新登录密码,可以为空，不为空的时候视为做密码修改", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.PostData, true)]
    [EWRAAddInput("usertype", "string", "用户类型", "默认为System(取值范围为System,Student,Teacher)", EFFC.Frame.Net.Base.Constants.RestInputPosition.PostData, true)]
    [EWRAAddInput("userno", "string", "用户编号,用户类型为Student或Teacher时为其对应的编号（此时为必输）", "默认为空", EFFC.Frame.Net.Base.Constants.RestInputPosition.PostData, true)]
    [EWRAAddInput("mobile", "string", "用户手机号", "默认为空", EFFC.Frame.Net.Base.Constants.RestInputPosition.PostData, true)]
    [EWRAAddInput("qq", "string", "用户手机号", "默认为空", EFFC.Frame.Net.Base.Constants.RestInputPosition.PostData, true)]
    [EWRAAddInput("avatar", "string", "用户头像url", "默认为空", EFFC.Frame.Net.Base.Constants.RestInputPosition.PostData, true)]
    [EWRAOutputDesc("返回结果", @"{
code:""success-成功，failed-失败"",
msg:""提示信息"",
function_no:""成功时候返回的登录账号""
}")]
    public override object patch(string id)
    {
        BeginTrans();
        string usertype = ComFunc.nvl(PostDataD.usertype);
        string userno = ComFunc.nvl(PostDataD.userno);
        string loginid = ComFunc.nvl(PostDataD.loginid);
        string loginname = ComFunc.nvl(PostDataD.loginname);
        string old_loginpass = ComFunc.nvl(PostDataD.old_loginpass);
        string loginpass = ComFunc.nvl(PostDataD.loginpass);
        string mobile = ComFunc.nvl(PostDataD.mobile);
        string qq = ComFunc.nvl(PostDataD.qq);
        string avatar = ComFunc.nvl(PostDataD.avatar);

        if (loginid == ""
            || loginname == "")
        {
            return new
            {
                code = "failed",
                msg = "登录账户、名称不可为空"
            };
        }
        if (loginpass == "" && old_loginpass == "")
        {
            return new
            {
                code = "failed",
                msg = "登录密码不可为空"
            };
        }

        var up = DB.NewMetaUnitParameter();

        var s = from t in DB.LamdaTable(up, "EXTEND_LOGIN", "a")
                where t.uid == id
                select t;
        if (!s.IsExists(up))
        {
            return new
            {
                code = "failed",
                msg = "数据不存在"
            };
        }
        dynamic info = (from t in DB.LamdaTable(up, "EXTEND_LOGIN", "a")
                        where t.uid == id
                        select t).GetQueryList(up).First();

        if ((from t in DB.LamdaTable(up, "EXTEND_LOGIN", "a")
             where t.loginid == loginid && t.uid != id
             select t).IsExists(up))
        {
            return new
            {
                code = "failed",
                msg = "登录账号已存在"
            };
        }

        s.Update(up, new
        {
            loginid = loginid,
            usertype = usertype,
            userno = userno,
            Mobile = mobile,
            loginname,
            QQ = qq,
            Avatar = avatar,
            Last_Id = TokenPayLoad.ID,
            Last_IP = ClientInfo.IP,
            Last_Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
        });
        //用户修改密码
        if (loginpass != "")
        {
            var encrypt_loginpass = ComFunc.AESEncrypt(loginpass);
            var encrypt_old_loginpass = ComFunc.AESEncrypt(old_loginpass);
            if (old_loginpass == "")
            {
                return new
                {
                    code = "failed",
                    msg = "旧密码不能为空"
                };
            }
            if (info.loginpass != encrypt_old_loginpass)
            {
                return new
                {
                    code = "failed",
                    msg = "旧密码不正确"
                };
            }
            if (info.loginpass == encrypt_loginpass)
            {
                return new
                {
                    code = "failed",
                    msg = "新密码不能与旧密码相同"
                };
            }
            if (info.lastpassword == encrypt_loginpass)
            {
                return new
                {
                    code = "failed",
                    msg = "新密码不能与以前的密码相同"
                };
            }

            s.Update(up, new
            {
                loginpass = encrypt_loginpass,
                lastpassword = info.loginpass,
                Last_Id = TokenPayLoad.ID,
                Last_IP = ClientInfo.IP,
                Last_Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
            });
        }


        CommitTrans();
        return new
        {
            code = "success",
            msg = "修改成功",
            function_no = id
        };
    }
    [EWRAEmptyValid("oldpw,newpw")]
    [EWRARoute("patch", "/login/{id}/changepassword")]
    [EWRARouteDesc("修改一个登录账号的密码")]
    [EWRAAddInput("id", "string", "账号UID码", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.Path, false)]
    [EWRAAddInput("oldpw", "string", "旧密码", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.PostData, false)]
    [EWRAAddInput("newpw", "string", "新密码", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.PostData, false)]
    public object Changepassword(string id)
    {
        var oldpw = ComFunc.AESEncrypt(ComFunc.nvl(PostDataD.oldpw));
        var newpw = ComFunc.AESEncrypt(ComFunc.nvl(PostDataD.newpw));

        if (oldpw == newpw)
        {
            return new
            {
                code = "failed",
                msg = "新密码不能与旧密码相同"
            };
        }
        var up = DB.NewMetaUnitParameter();
        var s = from t in DB.LamdaTable(up, "EXTEND_LOGIN", "a")
                where t.uid == id || t.loginid == id
                select t;
        if (!s.IsExists(up))
        {
            return new
            {
                code = "failed",
                msg = "用户不存在"
            };
        }

        dynamic info = s.GetQueryList(up).First();
        if (info.loginpass != oldpw)
        {
            return new
            {
                code = "failed",
                msg = "旧密码不正确"
            };
        }

        if (ComFunc.nvl(info.lastpassword) == newpw)
        {
            return new
            {
                code = "failed",
                msg = "新密码不能与已使用过密码一样"
            };
        }
        DB.QuickUpdate(up, "EXTEND_LOGIN", new
        {
            LoginPass = newpw,
            LastPassword = oldpw
        }, new
        {
            uid = info.uid
        });

        return new
        {
            code = "success",
            msg = "修改成功"
        };
    }
    [ActionAuth("Login")]
    [EWRARoute("get", "/loginuser/retion_list")]
    [EWRARouteDesc("获取其它用户类型列表")]
    [EWRAAddInput("usertype", "string", "类别", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.QueryString, false)]
    [EWRAOutputDesc("返回结果", @"{
code:""success-成功，failed-失败"",
msg:""提示信息"",
data:[{
uid:'GUID'
name:'姓名'
}]""成功时候返回的登录账号""
}")]
    object GetRelationUserList()
    {
        SetCacheEnable(false);
        var usertype = ComFunc.nvl(QueryStringD.usertype);
        var up = DB.NewMetaUnitParameter();
        object data = new List<object>();

        return new
        {
            code = "success",
            msg = "",
            data
        };
    }
    /// <summary>
    /// 创建登录账户
    /// </summary>
    /// <param name="metaup">元数据访问up</param>
    /// <param name="msg">返回的消息</param>
    /// <param name="loginid">登录账户</param>
    /// <param name="loginname">登录名称</param>
    /// <param name="userno">关联资料键值</param>
    /// <param name="userrole">登录角色，多个用逗号分隔，可以为角色编号或角色名称</param>
    /// <param name="loginpass">登录密码，默认123456</param>
    /// <param name="avatar">登录头像，默认为空</param>
    /// <param name="usertype">用户类型，默认为：User</param>
    /// <returns></returns>
    public bool CreateLogin(UnitParameter metaup,
        ref string msg,
        string loginid,
        string loginname,
        string userno,
        string userrole,
        string loginpass = "123456",
        string avatar = "",
        string usertype = "User")
    {
        loginpass = ComFunc.AESEncrypt(loginpass);
        if ((from t in DB.LamdaTable(metaup, "EXTEND_LOGIN", "a")
             where t.loginid == loginid
             select t).IsExists(metaup))
        {
            msg = "登录账号已存在";
            return false;
        }

        var loginlist = (from t in DB.LamdaTable(metaup, "EXTEND_LOGIN", "a")
                         where t.userno == userno
                         select t).GetQueryList(metaup);
        if (loginlist.Count > 0)
        {
            msg = "该用户已有登录账号";
            return false;
        }
        var rolelist = (from t in DB.LamdaTable(metaup, "EXTEND_ROLE", "a")
                        where t.roleno.within(userrole) || t.RoleName.within(userrole)
                        select t).GetQueryList(metaup);
        if (rolelist.Count <= 0)
        {
            msg = "无指定的角色";
            return false;
        }
        var uid = Guid.NewGuid().ToString();
        DB.QuickInsert(metaup, "EXTEND_LOGIN", new
        {
            UID = uid,
            LoginID = loginid,
            LoginName = loginname,
            UserNo = userno,
            UserType = usertype,
            LoginPass = loginpass,
            Avatar = avatar,
            add_id = "admin",
            add_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
            last_id = "admin",
            last_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
        });
        foreach (dynamic r in rolelist)
        {
            DB.QuickInsert(metaup, "EXTEND_ROLE_LOGIN", new
            {
                RoleNo = r.roleno,
                LoginUID = uid,
                add_id = "admin",
                add_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                last_id = "admin",
                last_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
            });
        }

        return true;
    }
    /// <summary>
    /// 删除登录账户
    /// </summary>
    /// <param name="metaup">元数据访问up</param>
    /// <param name="msg">返回的消息</param>
    /// <param name="id">登录账户或关联资料键值</param>
    /// <returns></returns>
    public bool DeleteLogin(UnitParameter metaup, ref string msg,
        string id)
    {
        var loginlist = (from t in DB.LamdaTable(metaup, "EXTEND_LOGIN", "a")
                         where t.userno == id || t.loginid == id
                         select t).GetQueryList(metaup);
        if (loginlist.Count <= 0)
        {
            msg = "无该登录资料";
            return false;
        }
        foreach (dynamic info in loginlist)
        {
            DB.QuickDelete(metaup, "EXTEND_ROLE_LOGIN", new
            {
                LoginUID = info.uid
            });
            DB.QuickDelete(metaup, "EXTEND_LOGIN", new
            {
                info.uid
            });
        }
        return true;
    }
}
}
